/*
 * @Author: your name
 * @Date: 2021-09-09 20:08:29
 * @LastEditTime: 2021-09-09 20:54:26
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \backstage-management-system\system\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import * as hooks from './hook'

const moduleFn = require.context('./routes', false, /\.js$/)
const routes = moduleFn.keys().reduce((pv, cv) => {
  let tmpRoute = moduleFn(cv).default
  // 使用es6新语法
  if (tmpRoute) Array.isArray(tmpRoute) ? pv.push(...tmpRoute) : pv.push(tmpRoute)
  return pv
}, [])

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 批量处理路由守卫
Object.keys(hooks).forEach(fnkey => router.beforeEach(hooks[fnkey]))

export default router